package com.wlza.sign;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.wlza.utils.Base64Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 吉大 HMAC_SM3签名服务类
 */
public class SignatureService {

    public static final Logger log = LoggerFactory.getLogger(SignatureService.class);

    private final static SignatureService instance=new SignatureService();

    public static SignatureService getInstance() {
        return instance;
    }

    private static KeyCodeInfo __macKey;  // 加解密密钥

    private CryptoConfiguration cryptoConfig= CryptoConfiguration.getInstance();
    public JiDaUtilService jiDaUtilService=JiDaUtilService.getInstance();


    public String signature(String str) {
        String keyCode = getKeyCode();
        String hmacUrl = cryptoConfig.getBaseUrl() + cryptoConfig.getHmacUri();

        Map<String, String> reqHeaders = jiDaUtilService.getReqHeaders();
        HashMap<String, Object> reqBody = new HashMap<>();
        reqBody.put("keyCode", keyCode);
        reqBody.put("algorithmParam", "HMAC_SM3");
        reqBody.put("data", Base64Util.encode(str));
        System.out.println("req==>>"+JSON.toJSONString(reqBody));
        JSONObject respBody = jiDaUtilService.sendPostReq(reqHeaders, reqBody, hmacUrl);
        JSONObject data = respBody.getJSONObject("data");
        return data.getStr("hmac");
    }

    public boolean verify(String str, String signature) {
        String signature1 = this.signature(str);
        return signature.equals(signature1);
    }

    /**
     * 获取密钥
     *
     * @return 密钥
     */
    private String getKeyCode() {
        // 0. 内存中存在密钥且未过期则直接返回
        if (__macKey != null && __macKey.getExpirationTime().after(new Date())) {
            return __macKey.getKeyCode();
        }

        // 1.数据库获取密钥
        if (__macKey == null) {
            // 2.1.1 没有密钥则从密钥服务器获取密钥
            __macKey = jiDaUtilService.getKeyCodeFromServer("SM4", 128, "1");
            return __macKey.getKeyCode();
        }
        // 2.2.1存在秘钥
        Date expirationTime = __macKey.getExpirationTime();
        int compare = DateUtil.compare(expirationTime, new Date());
        // 2.2.2判断是否过期
        if (compare <= 0) {
            // 2.2.3过期则从密钥服务器延长密钥
            __macKey = jiDaUtilService.extendKeyCodeExpirationTime(__macKey);
        }
        // 3返回密钥
        return __macKey.getKeyCode();
    }
}
